const { db } = require('../config/database');
const { logger } = require('../config/logger');

class BlueDeviceMangerService {

  /**
   * 验证设备是否有效
   * @param {string} macAddress MAC地址
   * @returns {Promise<Object|null>} 设备信息或null
   */
  async validateDevice(macAddress) {
    return new Promise((resolve, reject) => {
      if (!macAddress) {
        resolve(null);
        return;
      }

      const selectSQL = `
        SELECT * FROM blue_devices
        WHERE mac_address = ? AND device_status = 'active'
      `;

      db.get(selectSQL, [macAddress], (err, row) => {
        if (err) {
          logger.error('验证设备失败:', {
            error: err.message,
            macAddress
          });
          reject(err);
        } else if (!row) {
          logger.warn('设备未授权或不存在:', { macAddress });
          resolve(null);
        } else {
          // 更新最后使用时间
          this.updateLastUsedTime(macAddress).catch(updateErr => {
            logger.error('更新设备最后使用时间失败:', updateErr);
          });

          logger.info('设备验证成功:', {
            macAddress,
            deviceName: row.device_name,
            deviceType: row.device_type
          });

          resolve({
            id: row.id,
            macAddress: row.mac_address,
            deviceName: row.device_name,
            deviceType: row.device_type,
            deviceStatus: row.device_status,
            createdAt: row.created_at,
            lastUsedAt: row.last_used_at,
            notes: row.notes
          });
        }
      });
    });
  }

  /**
   * 添加新设备
   * @param {Object} deviceData 设备数据
   * @returns {Promise<Object>} 添加结果
   */
  async addDevice(deviceData) {
    return new Promise((resolve, reject) => {
      const {
        macAddress,
        deviceName,
        deviceType = 'bluetooth',
        notes = ''
      } = deviceData;

      if (!macAddress || !deviceName) {
        reject(new Error('MAC地址和设备名称不能为空'));
        return;
      }

      const currentTimestamp = Math.floor(Date.now() / 1000);

      const insertSQL = `
        INSERT INTO blue_devices
        (mac_address, device_name, device_type, device_status, created_at, updated_at, notes)
        VALUES (?, ?, ?, 'active', ?, ?, ?)
      `;

      db.run(insertSQL, [
        macAddress,
        deviceName,
        deviceType,
        currentTimestamp,
        currentTimestamp,
        notes
      ], function(err) {
        if (err) {
          if (err.code === 'SQLITE_CONSTRAINT_UNIQUE') {
            logger.warn('设备已存在:', { macAddress });
            reject(new Error('设备已存在'));
          } else {
            logger.error('添加设备失败:', {
              error: err.message,
              macAddress,
              deviceName
            });
            reject(err);
          }
        } else {
          logger.info('设备添加成功:', {
            id: this.lastID,
            macAddress,
            deviceName,
            deviceType
          });
          resolve({
            id: this.lastID,
            macAddress,
            deviceName,
            deviceType,
            success: true
          });
        }
      });
    });
  }

  /**
   * 删除设备（软删除，标记为inactive）
   * @param {string} macAddress MAC地址
   * @returns {Promise<Object>} 删除结果
   */
  async removeDevice(macAddress) {
    return new Promise((resolve, reject) => {
      const currentTimestamp = Math.floor(Date.now() / 1000);
      const updateSQL = `
        UPDATE blue_devices
        SET device_status = 'inactive', updated_at = ?
        WHERE mac_address = ?
      `;

      db.run(updateSQL, [currentTimestamp, macAddress], function(err) {
        if (err) {
          logger.error('删除设备失败:', {
            error: err.message,
            macAddress
          });
          reject(err);
        } else if (this.changes === 0) {
          logger.warn('设备不存在:', { macAddress });
          resolve({
            success: false,
            message: '设备不存在'
          });
        } else {
          logger.info('设备已删除:', {
            macAddress,
            changes: this.changes
          });
          resolve({
            success: true,
            message: '设备已删除',
            changes: this.changes
          });
        }
      });
    });
  }

  /**
   * 获取设备列表
   * @param {Object} options 查询选项
   * @returns {Promise<Array>} 设备列表
   */
  async getDevices(options = {}) {
    return new Promise((resolve, reject) => {
      const {
        status = 'active',
        limit = 50,
        offset = 0
      } = options;

      let whereClause = 'WHERE 1=1';
      const params = [];

      if (status) {
        whereClause += ' AND device_status = ?';
        params.push(status);
      }

      const selectSQL = `
        SELECT * FROM blue_devices
        ${whereClause}
        ORDER BY created_at DESC
        LIMIT ? OFFSET ?
      `;

      params.push(limit, offset);

      db.all(selectSQL, params, (err, rows) => {
        if (err) {
          logger.error('查询设备列表失败:', err);
          reject(err);
        } else {
          const devices = rows.map(row => ({
            id: row.id,
            macAddress: row.mac_address,
            deviceName: row.device_name,
            deviceType: row.device_type,
            deviceStatus: row.device_status,
            createdAt: row.created_at,
            createdAtReadable: new Date(row.created_at * 1000).toISOString(),
            updatedAt: row.updated_at,
            lastUsedAt: row.last_used_at,
            lastUsedAtReadable: row.last_used_at ? new Date(row.last_used_at * 1000).toISOString() : null,
            notes: row.notes
          }));

          logger.info(`查询到 ${devices.length} 个设备`);
          resolve(devices);
        }
      });
    });
  }

  /**
   * 更新设备信息
   * @param {string} macAddress MAC地址
   * @param {Object} updateData 更新数据
   * @returns {Promise<Object>} 更新结果
   */
  async updateDevice(macAddress, updateData) {
    return new Promise((resolve, reject) => {
      const allowedFields = ['device_name', 'device_type', 'device_status', 'notes'];
      const updateFields = [];
      const updateValues = [];

      // 构建更新字段
      for (const [key, value] of Object.entries(updateData)) {
        const dbField = key.replace(/([A-Z])/g, '_$1').toLowerCase();
        if (allowedFields.includes(dbField)) {
          updateFields.push(`${dbField} = ?`);
          updateValues.push(value);
        }
      }

      if (updateFields.length === 0) {
        reject(new Error('没有有效的更新字段'));
        return;
      }

      // 添加更新时间
      updateFields.push('updated_at = ?');
      updateValues.push(Math.floor(Date.now() / 1000));
      updateValues.push(macAddress);

      const updateSQL = `
        UPDATE blue_devices
        SET ${updateFields.join(', ')}
        WHERE mac_address = ?
      `;

      db.run(updateSQL, updateValues, function(err) {
        if (err) {
          logger.error('更新设备失败:', {
            error: err.message,
            macAddress,
            updateData
          });
          reject(err);
        } else if (this.changes === 0) {
          logger.warn('设备不存在:', { macAddress });
          resolve({
            success: false,
            message: '设备不存在'
          });
        } else {
          logger.info('设备更新成功:', {
            macAddress,
            updateData,
            changes: this.changes
          });
          resolve({
            success: true,
            message: '设备更新成功',
            changes: this.changes
          });
        }
      });
    });
  }

  /**
   * 更新设备最后使用时间
   * @param {string} macAddress MAC地址
   * @returns {Promise<void>}
   */
  async updateLastUsedTime(macAddress) {
    return new Promise((resolve, reject) => {
      const currentTimestamp = Math.floor(Date.now() / 1000);
      const updateSQL = `
        UPDATE blue_devices
        SET last_used_at = ?, updated_at = ?
        WHERE mac_address = ?
      `;

      db.run(updateSQL, [currentTimestamp, currentTimestamp, macAddress], function(err) {
        if (err) {
          reject(err);
        } else {
          resolve();
        }
      });
    });
  }

  /**
   * 获取设备统计信息
   * @returns {Promise<Object>} 统计信息
   */
  async getDeviceStats() {
    return new Promise((resolve, reject) => {
      const statsSQL = `
        SELECT
          COUNT(*) as total_devices,
          COUNT(CASE WHEN device_status = 'active' THEN 1 END) as active_devices,
          COUNT(CASE WHEN device_status = 'inactive' THEN 1 END) as inactive_devices,
          COUNT(CASE WHEN last_used_at > ? THEN 1 END) as recently_used_devices
        FROM blue_devices
      `;

      const weekAgo = Math.floor(Date.now() / 1000) - (7 * 24 * 60 * 60);

      db.get(statsSQL, [weekAgo], (err, row) => {
        if (err) {
          logger.error('查询设备统计失败:', err);
          reject(err);
        } else {
          resolve({
            totalDevices: row.total_devices,
            activeDevices: row.active_devices,
            inactiveDevices: row.inactive_devices,
            recentlyUsedDevices: row.recently_used_devices
          });
        }
      });
    });
  }
}

module.exports = new BlueDeviceMangerService();